package com.eshop.gen.service.impl;

import java.lang.invoke.SerializedLambda;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eshop.utils.FileUtil;
import cn.hutool.core.util.ZipUtil;
import java.io.File;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import com.eshop.gen.utils.GenUtil;
import com.eshop.exception.BadRequestException;
import com.eshop.gen.domain.GenConfig;
import java.io.Serializable;
import com.eshop.utils.StringUtils;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.Iterator;
import cn.hutool.core.util.ObjectUtil;
import java.util.Map;
import java.util.ArrayList;
import java.util.Collection;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import java.util.List;
import com.eshop.gen.domain.vo.TableInfo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eshop.utils.PageUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import com.eshop.gen.service.GeneratorService;
import com.eshop.gen.domain.ColumnConfig;
import com.eshop.gen.service.mapper.ColumnInfoMapper;
import com.eshop.common.service.impl.BaseServiceImpl;

@Service
public class GeneratorServiceImpl extends BaseServiceImpl<ColumnInfoMapper, ColumnConfig> implements GeneratorService
{
    public Object getTables() {
        return ((ColumnInfoMapper)this.baseMapper).selectTables();
    }
    
    public Object getTables(final String name, Integer page, final Integer size) {
        IPage<TableInfo> pages = null;
        if (page >= 0) {
            ++page;
        }
        final Page<TableInfo> pageModel = (Page<TableInfo>)new Page((long)page, (long)size);
        pages = ((ColumnInfoMapper)this.baseMapper).selectTablePage(pageModel, name);
        final Integer totalElements = 0;
        return PageUtil.toPage(pages.getRecords(), pages.getTotal());
    }
    
    public List<ColumnConfig> getColumns(final String tableName) {
        List<ColumnConfig> columnInfos = this.list(( Wrappers.<ColumnConfig>lambdaQuery().eq(ColumnConfig::getTableName, tableName)).orderByAsc(ColumnConfig::getId));
        if (CollectionUtil.isNotEmpty((Collection)columnInfos)) {
            return columnInfos;
        }
        columnInfos = this.query(tableName);
        this.saveBatch((Collection)columnInfos);
        return columnInfos;
    }
    
    public List<ColumnConfig> query(final String tableName) {
        final List<ColumnConfig> columnInfos = new ArrayList<ColumnConfig>();
        final List<Map<String, Object>> result = ((ColumnInfoMapper)this.baseMapper).queryByTableName(tableName);
        for (final Map<String, Object> map : result) {
            columnInfos.add(new ColumnConfig(tableName, map.get("COLUMN_NAME").toString(), "NO".equals(map.get("IS_NULLABLE").toString()), map.get("DATA_TYPE").toString(), ObjectUtil.isNotNull(map.get("COLUMN_COMMENT")) ? map.get("COLUMN_COMMENT").toString() : null, ObjectUtil.isNotNull(map.get("COLUMN_KEY")) ? map.get("COLUMN_KEY").toString() : null, ObjectUtil.isNotNull(map.get("EXTRA")) ? map.get("EXTRA").toString() : null));
        }
        return columnInfos;
    }
    
    public void sync(final List<ColumnConfig> columnInfos, final List<ColumnConfig> columnInfoList) {
        for (final ColumnConfig columnInfo : columnInfoList) {
            final List<ColumnConfig> columns = new ArrayList<ColumnConfig>((Collection<? extends ColumnConfig>)columnInfos.stream().filter(c -> c.getColumnName().equals(columnInfo.getColumnName())).collect(Collectors.toList()));
            if (CollectionUtil.isNotEmpty((Collection)columns)) {
                final ColumnConfig column = columns.get(0);
                column.setColumnType(columnInfo.getColumnType());
                column.setExtra(columnInfo.getExtra());
                column.setKeyType(columnInfo.getKeyType());
                if (StringUtils.isBlank((CharSequence)column.getRemark())) {
                    column.setRemark(columnInfo.getRemark());
                }
                this.saveOrUpdate(column);
            }
            else {
                this.save(columnInfo);
            }
        }
        for (final ColumnConfig columnInfo : columnInfos) {
            final List<ColumnConfig> columns = new ArrayList<ColumnConfig>(columnInfoList.stream().filter(c -> c.getColumnName().equals(c.getColumnName())).collect(Collectors.toList()));
            if (CollectionUtil.isEmpty((Collection)columns)) {
                this.removeById((Serializable)columnInfo.getId());
            }
        }
    }
    
    public void save(final List<ColumnConfig> columnInfos) {
        this.saveOrUpdateBatch((Collection)columnInfos);
    }
    
    public void generator(final GenConfig genConfig, final List<ColumnConfig> columns) {
        if (genConfig.getId() == null) {
            throw new BadRequestException("请先配置生成器");
        }
        try {
            GenUtil.generatorCode(columns, genConfig);
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new BadRequestException("生成失败，请手动处理已生成的文件");
        }
    }
    
    public ResponseEntity<Object> preview(final GenConfig genConfig, final List<ColumnConfig> columns) {
        if (genConfig.getId() == null) {
            throw new BadRequestException("请先配置生成器");
        }
        final List<Map<String, Object>> genList = GenUtil.preview(columns, genConfig);
        return (ResponseEntity<Object>)new ResponseEntity(genList, HttpStatus.OK);
    }
    
    public void download(final GenConfig genConfig, final List<ColumnConfig> columns, final HttpServletRequest request, final HttpServletResponse response) {
        if (genConfig.getId() == null) {
            throw new BadRequestException("请先配置生成器");
        }
        try {
            final File file = new File(GenUtil.download(columns, genConfig));
            final String zipPath = file.getPath() + ".zip";
            ZipUtil.zip(file.getPath(), zipPath);
            FileUtil.downloadFile(request, response, new File(zipPath), true);
        }
        catch (IOException e) {
            throw new BadRequestException("打包失败");
        }
    }
}
